import {Component, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material';
import { RepairaddComponent } from '../repairadd/repairadd';
import {tap} from 'rxjs/operators';
import { Deliver, RepairStatus, RepairStatusMap } from '../../models/Deliver';
import { DeliverService } from '../../service/deliverService';
import { RepairService } from '../../service/repairService';
import {Asset, StatusNameMap} from '../../models/Asset';
import { RepaireditComponent} from '../repairedit/repairedit';
import { Loginauth } from '../../service/loginauth';
import {IActionMapping, ITreeOptions, TreeComponent} from 'angular-tree-component';
import {environment} from '../../environments/environment';
import {Department} from '../../models/Department';
import {AssetType} from '../../models/AssetType';
import {User} from '../../models/User';
import {FormControl} from '@angular/forms';
import {AssetService} from '../../service/assetService';
import {DepartmentService} from '../../service/departmentService';
import {UserService} from '../../service/userService';
import {Moment} from 'moment';
declare var $: any;
@Component({
  templateUrl: './assetrepair.html',
  styleUrls: ['./assetrepair.css']
})
export class AssetrepairComponent implements OnInit {
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  environment = environment;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  repairs: Deliver[];
  deliver: Deliver;
  users: User[];
  assetTypes: AssetType[];
  departments: Department[];
  departmentid: number;
  total: number;
  isAdmin: boolean;
  page: number = 1;
  pageSize: number = 5;
  StatusNameMap = StatusNameMap;
  RepairStatusMap = RepairStatusMap;
  asset: Asset;
  appearSearch: boolean = false;
  beginCtrl = new FormControl();
  endCtrl = new FormControl();
  start_createDate: any;
  end_createDate: any;
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.asset.assetType = node.data.GDZCLB_DM;
        this.assettypeName = node.data.GDZCLBMC;
        this.typetree = false;
      }
    }
  };
  colsone = [ 'repairNum',  'repairStatus', 'repaircreateDate'];
  colstwo = ['reason', 'repairusername', 'departName', 'username',  'money', 'repairremark', 'assetName', 'assetStatus', 'assetCode', 'assetType', 'createDate', 'brand', 'source', 'version', 'sourceComefrom',
    'assetPrice', 'buyDate', 'snNum', 'remark']
  constructor(private route: ActivatedRoute, private dialog: MatDialog,
              private deliverService: DeliverService,
              private repairService: RepairService,
              private loginauthService: Loginauth,
              private assetService: AssetService,
              private departmentService: DepartmentService,
              private userService: UserService) {

  }
  ngOnInit() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assetService.getAssetTypes().subscribe((res) => {
      this.assetTypes = res.res;
      for (let i = 0; i < this.assetTypes.length; i++) {
        this.nodes.push({GDZCLBMC: this.assetTypes[i].GDZCLBMC, GDZCLB_DM: this.assetTypes[i].GDZCLB_DM});
      }
      this.nodes.forEach((node, index) => {
        node.children = this.assetTypes[index].children;
      })
    })
    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
    this.departmentService.getAllDepartments().subscribe((res) => {
      this.departments = res.res;
    })
    this.loginauthService.checkAdmin().subscribe((isAdmin: boolean) => {
      this.isAdmin = isAdmin;
      if (this.isAdmin) {
        this.colstwo = ['reason', 'repairusername', 'departName', 'username',  'money', 'repairremark', 'assetName', 'assetStatus', 'assetCode', 'assetType', 'createDate', 'brand', 'source', 'version', 'sourceComefrom',
          'assetPrice', 'buyDate', 'snNum', 'remark', 'operate']
      }
    })
    this.deliver = new Deliver();
    this.update().subscribe((res) => {
      window.setInterval(() => {
        this.setHeight();
      }, 100);
    });
  }
  setHeight() {
    for ( let i = 0; i < this.repairs.length; i++) {
      const id = this.repairs[i];
      $('#' + id.repairNum).height(id.list.length * 48 - 1.4 + 'px');
    }
  }
  onopenAdd() {
    const dialogRef = this.dialog.open(RepairaddComponent, {
      width: '900px',
      height: '650px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.update().subscribe();
    })
  }
  onOpenEdit(repairs) {
    const dialogRef = this.dialog.open(RepaireditComponent, {
      width: '900px',
      height: '650px',
      data: {
        repairs: repairs
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.update().subscribe();
    })
  }

  update() {
    const options: any = {};
    if (this.asset.assetName) {options.assetName = this.asset.assetName}
    if (this.asset.sysDepartment.id) {options.assetDepartmentId = this.asset.sysDepartment.id; }
    if (this.asset.sysUser.id) {options.assetUserId = this.asset.sysUser.id; }
    if (this.start_createDate) {const start = this.start_createDate.toDate(); options.start_createDate = start; }
    if (this.end_createDate) {const end = this.end_createDate.toDate(); options.end_createDate = end ; }
    if (this.asset.assetType) {options.assetType = this.asset.assetType; }
    return this.repairService.getList(this.page, this.pageSize, options).pipe(tap((res) => {
      this.repairs = res.res;
      this.total = res.total;
    }));
  }
  trackById(index: number, item: any) {
    return item.id;
  }
  onPageChanged(page: number) {
    this.page = page;
    this.update().subscribe();
  }
  search() {
    if (this.deliver.repairNum) {
      this.repairService.getone(this.deliver.repairNum).subscribe((res) => {
        this.repairs = [];
        this.repairs.push(res.res);
      })
    } else{
      this.update().subscribe();
    }
  }
  changeDepartment(departmentId) {
    this.departmentid = departmentId;
    this.getUsers();
  }
  getUsers() {
    this.userService.getUsers(1, 5, this.departmentid).subscribe((res) => {
      this.users = res.res;
    })
  }
  appearSearchbox() {
    this.appearSearch = true;
  }
  bigsearch() {
    this.appearSearch = false;
    this.update().subscribe();
  }
  reset() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assettypeName = '';
    this.beginCtrl = new FormControl();
    this.endCtrl = new FormControl();
    this.start_createDate = false;
    this.end_createDate = false;
  }
  closesearch() {
    this.appearSearch = false;
  }
  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }
  onSwitchDate(_: Moment) {
    this.start_createDate = this.beginCtrl.value;
    this.end_createDate = this.endCtrl.value;
  }
}
